package cn.fws.meap.community.service.impl;

import java.math.BigDecimal;
import java.util.*;

import cn.fws.framework.utils.StringUtils;
import cn.fws.meap.community.entity.*;
import cn.fws.meap.community.enums.*;
import cn.fws.meap.community.mapper.ProblemResourcesMapper;
import cn.fws.meap.community.mapper.ResourcesMapper;
import cn.fws.meap.community.service.*;
import cn.fws.meap.community.vo.ProblemListVo;
import cn.fws.meap.community.vo.Details;
import cn.fws.meap.system.constants.QiNiuParam;
import cn.fws.meap.user.entity.Collect;
import cn.fws.meap.user.mapper.CollectMapper;
import cn.fws.meap.user.service.ICollectService;
import cn.fws.meap.utils.articleUtil.ProblemResourceUtil;
import cn.fws.meap.utils.QiNiuUtil;

import cn.fws.meap.utils.logBug.SysLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.fws.framework.utils.ConvertUtils;
import cn.fws.framework.utils.UUIDUtils;

import cn.fws.meap.community.mapper.ProblemMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 问题 服务层实现
 *
 * @author chenkh
 * @date 2019-03-07
 */
@Service
@Transactional
public class ProblemServiceImpl implements IProblemService {

    @Autowired
    private ProblemMapper problemMapper;
    @Autowired
    private IResourcesService resourcesService;
    //中间表
    @Autowired
    private ProblemResourcesMapper problemResourcesMapper;
    @Autowired
    private DetailsUtils<Problem> detailsUtils;
    @Autowired
    private IProblemResourcesService problemResourcesService;
    @Autowired
    private ResourcesMapper resourcesMapper;

    @Autowired
    private IEvaluateService evaluateService;

    @Autowired
    private ICreationService creationService;
    @Autowired
    private CollectMapper collectMapper;




    /**
     * 查询问题信息
     *
     * @param id 问题ID
     * @return 问题信息
     */
    @Override
    public Problem selectById(String id) {
        return problemMapper.selectById(id);
    }

    /**
     * 查询问题列表
     *
     * @param hotProblem 问题信息
     * @return 问题集合
     */
    @Override
    public List<ProblemListVo> selectList(String hotProblem) {
        List<ProblemListVo> problemList = problemMapper.selectList(hotProblem);
        for (ProblemListVo problems : problemList) {

        	problems.setProblemMsg(QiNiuUtil.getFileMsg(problems.getProblemMsg()));
		}
        return problemList;

    }

    /**
     * 新增问题
     *
     * @param problem 问题信息
     * @return 结果
     */
    @Override
    public String insert(Problem problem) {

        String uuid = UUIDUtils.getUUID();
        //问题是否已解决
        problem.setIsSolve(ProblemIsSolveEnum.NO_SOLVE.getCode());

        problem.setIsDelete("0");
        //最新问题时间
        problem.setCreateTime(new Date());
        //设置主键
        problem.setId(uuid);

        //定义图片地址，资源id
        String problemImgAddress;
        //注意两个问题图像problem_img可能有多个地址要字符串切割，切割完成存到七牛云
        String problemImgs = problem.getProblemImg();
        String[] splitProblemImg = problemImgs.split(",");
        //调用资源方法吧地址存入到resources中  存入3个参数 【资源地址，资源类型，openid】
        for (String problemImg : splitProblemImg) {
            //传过来的图片添加一个地址七牛云
            StringBuilder stringBuilder=new StringBuilder().append(QiNiuParam.IMG_URL).append(problemImg);
           problemImgAddress= resourcesService.addResources(stringBuilder.toString(),ResourcesTypeEnum.IMAGE.getCode(),problem.getOpenid());
            //把多个资源表id和问题表id存入中间表
           problemResourcesService.insert(problemImgAddress,uuid);
        }
        //在问题表里【暂时】不添加问题图片这个字段
        problem.setProblemImg("");

        //问题内容problem_msg存到七牛云中
        String problemMsg = problem.getProblemMsg();
        String problemMsgResource= QiNiuUtil.uploadFile(QiNiuParam.MEAP_DOCUMENT, problemMsg);
        //问题内容存入资源表中
        String problemMsgAdderss=resourcesService.addResources(problemMsgResource,ResourcesTypeEnum.TEXT.getCode(),problem.getOpenid());

        //把资源表中的id存入到问题表中的内容字段
        problem.setProblemMsg(problemMsgAdderss);
        problemMapper.insert(problem);


        //添加创作记录表
        Creation creation=new Creation();
        creation.setArticleId(uuid);
        creation.setArticleType(ArticleTypeEnum.PROBLEM.getCode());
        creation.setOpenid(problem.getOpenid());
        System.out.println("创作记录表+++"+creation.toString());
        creationService.insert(creation);


        return uuid;
    }

    private void saveProblemResourcesToMidTable(Problem problem) {
        //	获取ID
        String problemId = problem.getId();
        ArrayList<ProblemResources> problemResourcesList = new ArrayList<>();
        Date date = new Date();
        //保存问题 图片资源
        addProResToList(problemId, problem.getProblemImg(), problemResourcesList, date);
        problemResourcesMapper.insertList(problemResourcesList);

    }

    /**
     * 修改问题
     *
     * @param problem 问题信息
     * @return 结果
     */
    @Override
    public int update(Problem problem) {
        // 获取ID
        String problemId = problem.getId();
        // 获取openID
        String openid = problem.getOpenid();
        // 设置修改时间
        problem.setUpdateTime(new Date());
        //	获取新的文本地址
        String newMsgAddress = problem.getProblemMsg();
        //	获取新的图片地址
        String newImgAddress = problem.getProblemImg();

        String oldMsgId = problemMapper.getMsgIdById(problemId);
        String msgId = resourcesService.updateMsgResources(oldMsgId, openid, newMsgAddress, ResourcesTypeEnum.IMAGE.getCode());
        problem.setProblemMsg(msgId);

        // 删除旧版关联的资源对象
        resourcesService.removeResources(problemId);
        problem.setProblemImg(resourcesService.saveOtMResource(newImgAddress, openid, ResourcesTypeEnum.IMAGE.getCode()));
        //	建立管理关系
        saveProblemResourcesToMidTable(problem);
        return problemMapper.update(problem);
    }

    /**
     * 删除问题对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteByIds(String ids) {
        return problemMapper.deleteByIds(ConvertUtils.toStrArray(ids));
    }

    @Override
    public List<Details<Problem>> selectListNew() {
        List<Problem> problemList = problemMapper.selectListNew();
        //传入问题列表,返回问题详情列表
        return getDetailsList(problemList);

    }

    /**
     * 传入问题列表,返回问题详情列表
     *
     * @param problemList
     * @return
     */
    @Override
    public List<Details<Problem>> getDetailsList(List<Problem> problemList) {
        List<Details<Problem>> detailsList = new ArrayList<>();
        for (Problem pro : problemList) {
            //获取问题ID
            String id = pro.getId();
            //获取openID
            String openid = pro.getOpenid();
            //通过ID和openID获取details
            Details<Problem> details = detailsUtils.getDetails(id, openid, DetailsTypeEnum.IS_PROBLEM.getCode());
            //将问题添加到details
            details.setT(pro);
            detailsList.add(details);

        }
        return detailsList;

    }
    public void addProResToList(String articleId, String
            resIds, ArrayList<ProblemResources> problemResources, Date date) {
        ProblemResourceUtil.addProRes(articleId,resIds,problemResources,date);
    }
    
    /**
     * 查询问题详情
     *
     * @param id 问题ID
     * @return 问题信息
     */
    @SysLog
    @Override
    public ProblemListVo selectProblemById(String id,String openId) {
        List pictures=new ArrayList();
    	ProblemListVo problemVo = problemMapper.selectProblemById(id);

        //是否是当前用户发布的问题，是否显示采纳
        if(openId.equals(problemVo.getOpenid())){
            problemVo.setShowAdopt(true);
        }

        Map map = problemMapper.problemEvaluateCount(id);
        Set set = map.keySet();
        for (Object o : set) {
            BigDecimal o1 =(BigDecimal) map.get(o);
            if("evaluate_count".equals(o)){

                problemVo.setEvaluateCount(o1.toString());
            }else if("badEvaluateCount".equals(o)){
                problemVo.setBadEvaluateCount(o1.toString());
            }
        }
        System.out.println("问题内容地址-----"+problemVo.getProblemMsg());
    	String fileMsg = QiNiuUtil.getFileMsg(problemVo.getProblemMsg());
        problemVo.setProblemMsg(fileMsg);
        List<Resources> problemListPicture= resourcesMapper.selectProblemListPicture(id);

        for (Resources resources1 : problemListPicture) {
            pictures.add(resources1.getResAddress());
        }
        problemVo.setPicture((pictures));
        //查询当前用户有没有点赞
        Boolean flag = evaluateService.selectOpenId(openId, id);
        System.out.println("第一次查没查到这条数据"+flag);
        problemVo.setFlag(flag);

        //有 查看当前用户对这个问题是赞还是踩

        if(flag){
            Evaluate evaluateStatus=evaluateService.selectEvaluateStatus(id,openId);
            problemVo.setEvaluateStatus(evaluateStatus.getEvaluateType());
        }

        Collect collect = collectMapper.selectByarticleIdAndOpenId(id, openId);
        if(StringUtils.isNull(collect)){
            problemVo.setCollectStatus(CollectionTypeEnum.NO_COLLECTION.getCode());
        }else {
            problemVo.setCollectStatus(CollectionTypeEnum.COLLECTION.getCode());
        }
        return problemVo;
    }

}
